# Illustrating the use of ExternalProject
#
# SPDX-License-Identifier: MIT

cmake_minimum_required(VERSION 3.21)

project(
    external_project_example
    VERSION 1.0
    DESCRIPTION
        "A simple C++ project to demonstrate fetching external content"
    LANGUAGES CXX
)
include(ExternalProject)

ExternalProject_Add(
  bertrand_downloaded
  URL https://github.com/bernedom/bertrand/archive/refs/tags/0.0.17.tar.gz
  URL_HASH MD5=354141c50b8707f2574b69f30cef0238
  
  INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/bertrand_downloaded_install
  CMAKE_ARGS -D BERTRAND_BUILD_TESTING=OFF             
             -D CMAKE_INSTALL_PREFIX=<INSTALL_DIR>
)

ExternalProject_Get_Property(bertrand_downloaded INSTALL_DIR)
set(BERTRAND_DOWNLOADED_INSTALL_DIR "${INSTALL_DIR}")

# Add an extra step after the build step to extract and archive the license file
ExternalProject_Add_Step(bertrand_downloaded copy_license 
                        COMMAND ${CMAKE_COMMAND} -E tar "cvzf" 
                                ${CMAKE_CURRENT_BINARY_DIR}/licenses.tar.gz <SOURCE_DIR>/LICENSE 
                        DEPENDEES build
                        ALWAYS YES
)

# Create a target to build an executable
add_executable(external_project_example)
# set the c++ version required

target_compile_features(
    external_project_example
    PRIVATE cxx_std_17
)
# Add source files to 'external_project_example' target
target_sources(
    external_project_example
    PRIVATE src/main.cpp
)
# make the executable to be built depend on the external project
# to force downloading first
add_dependencies(external_project_example bertrand_downloaded)

# make the header file for bertrand available
target_include_directories(external_project_example PRIVATE 
                          ${BERTRAND_DOWNLOADED_INSTALL_DIR}/include
)
